package com.my.interview.lock;

import java.util.concurrent.atomic.AtomicReference;

/**
 * 可重入的自旋锁
 */
public class AtomicLock2 {

    private int count = 0;
    private AtomicReference<Thread> owner = new AtomicReference<>();

    public void lock(){
        Thread current = Thread.currentThread();
        if(current == owner.get()){
            count++;
            return;
        }
        while (!owner.compareAndSet(null, current)){
            System.out.println("--------");
        }
    }


    public void unlock(){
        Thread current = Thread.currentThread();

        if(current == owner.get()){
            if(count != 0){
                count --;
            }else{
                owner.compareAndSet(current, null);
            }
        }
    }
}
